package com.commerceerp.system.service;

import com.commerceerp.system.entity.*;
import com.commerceerp.system.mapper.GoodMapper;
import com.commerceerp.system.mapper.OrderMapper;
import com.commerceerp.system.mapper.ShopMapper;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.DateUtil;
import com.commerceerp.system.util.StringUtils;
import com.google.common.collect.Lists;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/10/010.
 */
@Service
public class WishService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodMapper goodMapper;

    //测试
    //private String wishUrl = "https://sandbox.merchant.wish.com/api/v2";
    //正式
    private String wishUrl = "https://merchant.wish.com/api/v2";

    //同步wish订单
    public ApiResult getWishOrder(String userId) {
        List<ShopWish> shopWishs = shopMapper.getShopWish(userId);
        if (shopWishs == null || shopWishs.size() == 0) {
            logger.info("");
        }
        for (ShopWish shopWish : shopWishs) {
            StringBuffer url = new StringBuffer(wishUrl + "/order/multi-get?");
            if (StringUtils.isEmpty(shopWish.getToken())) {
                continue;
            }
            url.append("access_token=" + shopWish.getToken());
            url.append("&since=" + DateUtil.getDateBeforeFifteen(DateUtil.getYMDDate()));
            url.append("&start=" + "0");
            url.append("&limit=" + "100");
            String result = StringUtils.httpURLConectionGET(url.toString());
            while (StringUtils.isNotEmpty(result)) {
                JSONObject json = JSONObject.fromObject(result);
                result = "";
                int code = json.getInt("code");
                if (code == 0) {
                    JSONArray data = json.getJSONArray("data");
                    //遍历数组获取元素----对象
                    analysisJsonOrder(shopWish.getId(), shopWish.getShopUserId(), data);
                    if (data.size() >= 100) {//可能有第二页
                        JSONObject paging = json.optJSONObject("paging");//下一页
                        String next = paging.getString("next");
                        result = StringUtils.httpURLConectionGET(next);
                        continue;
                    }
                } else {
                    return new ApiResult(405, "https://merchant.wish.com/oauth/authorize?client_id=" + shopWish.getClientId(), shopWish.getShopName() + "店铺授权码过期，请重新授权");
                }
            }
        }
        return new ApiResult(200, "同步完成");
    }

    //将json转换为order数据
    public void analysisJsonOrder(String orderStoreId, String shopUserId, JSONArray data) {
        for (int i = 0; i < data.size(); i++) {
            JSONObject child = data.getJSONObject(i);
            JSONObject order = child.optJSONObject("Order");//

            OrderVo orderInfo = new OrderVo();
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            GoodInfo goodInfo = new GoodInfo();
            orderInfo.setOrderStoreId(orderStoreId);
            orderInfo.setShopUserId(shopUserId);
            orderInfo.setOrderChannel("3");
            goodInfo.setGoodPlatformType("3");
            if (order.has("last_updated")) {
                String updTime = order.getString("last_updated");//最后更新时间
                orderInfo.setUpdTime(updTime.replace("T", " "));
            }
            if (order.has("quantity")) {
                String quantity = order.getString("quantity");//购买数量
                orderDetailVo.setOrderGoodNumber(Integer.valueOf(quantity));
            }
            if (order.has("price")) {
                String price = order.getString("price");//单价
                orderDetailVo.setOrderGoodPrice(price + "USD");
                goodInfo.setGoodPurchasePrice(Double.valueOf(price));
                //兑换成人民币
                orderInfo.setOrderMoneyCny(price);
            }

            if (order.has("product_image_url")) {
                String productImageUrl = order.getString("product_image_url");//商品图片
                orderDetailVo.setOrderImageUrl(productImageUrl);
                goodInfo.setGoodPicPath(productImageUrl);
            }

            if (order.has("sku")) {
                String sku = order.getString("sku");//sku
                orderDetailVo.setOrderSku(sku);
                goodInfo.setGoodPlatformSku(sku);
            }

            if (order.has("order_total")) {
                String orderTotal = order.getString("order_total");//订单的总价值
                orderInfo.setOrderMoney(orderTotal);
            }

            if (order.has("product_id")) {
                String productId = order.getString("product_id");//产品id
                orderDetailVo.setOrderGoodId(productId);
                goodInfo.setGoodPlatformId(productId);
                goodInfo.setGoodUrl("https://www.wish.com/c/" + productId);
            }

            if (order.has("order_id")) {
                String orderId = order.getString("order_id");//订单id
                orderInfo.setOrderId(orderId);
            }

            if (order.has("buyer_id")) {
                String buyerId = order.getString("buyer_id");//买家id
                orderInfo.setOrderBuyerId(buyerId);
            }

            if (order.has("state")) {
                String orderStatus = order.getString("state");//订单状态 APPROVED发货 SHIPPED已发货 REFUNDED退款 REQUIRE_REVIEW：审核中，请勿发货
                String status = "";
                if (StringUtils.equals(orderStatus, "APPROVED")) {
                    status = "3";
                } else if (StringUtils.equals(orderStatus, "SHIPPED")) {
                    status = "4";
                } else if (StringUtils.equals(orderStatus, "REFUNDED")) {
                    status = "5";
                } else if (StringUtils.equals(orderStatus, "REQUIRE_REVIEW")) {
                    status = "1";
                }
                orderInfo.setOrderStatus(status);
            }

            if (order.has("size")) {
                String size = order.getString("size");//订购产品的尺寸
                goodInfo.setGoodSize(size);
            }

            if (order.has("product_name")) {
                String productName = order.getString("product_name");//产品名称
                goodInfo.setGoodPlatformName(productName);
            }

            //根据平台商品id，获取本系统商品ID
            String goodId = goodMapper.getGoodIdByPlatformId(goodInfo.getGoodPlatformId());
            if (StringUtils.isEmpty(goodId)) {
                goodInfo.setGoodId(StringUtils.getUUID());
                goodMapper.saveNewSystemGood(goodInfo);
            }

            if (order.has("order_time")) {
                String orderTime = order.getString("order_time");//订单发出的日期和时间
                orderInfo.setOrderDownTime(orderTime.replace("T", " "));
            }

            if (order.has("buyer_id")) {
                String buyerId = order.getString("buyer_id");//买家
                orderInfo.setOrderBuyerId(buyerId);
            }

            if (order.has("ShippingDetail")) {
                JSONObject shippingDetail = order.optJSONObject("ShippingDetail");//收件人信息

                if (shippingDetail.has("phone_number")) {
                    String phoneNumber = shippingDetail.getString("phone_number");//收件人号码
                    orderInfo.setAddressPhone(phoneNumber);
                }
                if (shippingDetail.has("city")) {
                    String city = shippingDetail.getString("city");//收件城市
                    orderInfo.setAddressCity(city);
                }

                if (shippingDetail.has("state")) {
                    String state = shippingDetail.getString("state");//收件地区
                    orderInfo.setAddressProvince(state);
                }

                if (shippingDetail.has("name")) {
                    String name = shippingDetail.getString("name");//收件人
                    orderInfo.setAddressRecipients(name);
                }

                if (shippingDetail.has("country")) {
                    String country = shippingDetail.getString("country");//收件国家
                    orderInfo.setAddressCountry(country);
                }

                if (shippingDetail.has("zipcode")) {
                    String zipcode = shippingDetail.getString("zipcode");//邮编
                    orderInfo.setAddressPostcode(zipcode);
                }

                if (shippingDetail.has("street_address1")) {
                    String streetAddress = shippingDetail.getString("street_address1");//收件地址
                    orderInfo.setAddressLocationA(streetAddress);
                }

                if (shippingDetail.has("street_address2")) {
                    String streetAddress2 = shippingDetail.getString("street_address2");//收件地址2
                    orderInfo.setAddressLocationB(streetAddress2);
                }
            }

            //检索订单id
            String id = orderMapper.getOrderIdId(orderInfo.getOrderId());
            if (StringUtils.isEmpty(id)) {//新增订单
                StringUtils.getOrderSerialNumber(orderInfo);
                orderInfo.insert();
                orderMapper.insert(orderInfo);
                orderDetailVo.setOrderId(orderInfo.getId());
                orderDetailVo.insert();
                //插入订单明细
                List<OrderDetailVo> detailVos = Lists.newArrayList();
                detailVos.add(orderDetailVo);
                orderMapper.insertOrderDetail(detailVos);
            } else {//修改订单
                orderInfo.setId(id);
                orderMapper.update(orderInfo);
            }

        }

    }

    /**
     * @param name                向愿望用户显示的产品名称（必填）
     * @param description         产品描述。不应该包含HTML。如果您想要换行，请使用“\ n”。（必填）
     * @param declared_name       物流申报的产品名称
     * @param declared_local_name 产品名称用当地语言写成，用于物流申报
     * @param pieces              与此商品相关的件数
     * @param tags                用逗号分隔的描述产品的字符串列表。只允许10个。任何过去10的标签都会被忽略（必填）。
     * @param sku                 系统用来识别此产品的唯一标识符（必填）
     * @param color               可选产品的颜色。例如：红色，蓝色，绿色
     * @param size                可选产品的大小。例如：大，中，小，5,6,7.5
     * @param inventory           此产品的物理量最多为500,000（必填）
     * @param price               当用户购买一个的变化的价格，最多100,000（必填）
     * @param shipping            当用户购买一件时，产品的运送，最多1000件（必填）
     * @param msrp                可选的制造商建议零售价。建议使用此字段，因为它会在Wish上显示为删除线价格，并显示在产品的销售价格之上。
     * @param shipping_time       可选运送到达买方所需的时间。还请考虑完成和装运物品所需的时间。提供天数的时间范围。下限不得少于2天。上限必须在下限后至少5天。例如：15-20
     * @param main_image          您产品照片的网址。直接链接到图像，而不是它所在的页面。我们接受JPEG，PNG或GIF格式。图像的大小至少应为100 x 100像素。
     * @param parent_sku          可选在定义产品的变体时，我们必须知道将变体附加到哪个产品。parent_sku是稍后您在使用添加产品变体API时可以使用的产品的唯一ID。
     * @param brand               可选品牌或您的产品的制造商
     * @param landing_page_url    包含产品详细信息的网站上的可选网址
     * @param upc                 可选的 12位通用产品代码（UPC） - 不包含任何字母或其他字符
     * @param extra_images        您的产品额外照片的可选网址。直接链接到图像，而不是它所在的页面。main_image的规则相同。您可以指定一个或多个由字符'|'分隔的附加图像。额外图像的总数加上变化图像的数量不得超过20。
     * @param max_quantity        可选每件订单的最大产品数量。
     * @param length              可选包装发运给客户的产品长度（以厘米为单位）
     * @param width               可选您的产品将被包装运送给客户的宽度（以厘米为单位）
     * @param height              可选您的产品将被包装以运送给客户的高度（以厘米为单位）
     * @param weight              可选您的产品的重量将包装发货给客户（单位为g）
     * @param declared_value      可选您的产品的价格将被宣布为定制。
     * @param hscode              可选的用于定制声明的统一系统代码。
     * @param origin_country      产品制造的可选国家。国家代码应遵循ISO 3166 Alpha-2代码。例如：CN，US
     * @param has_powder          可选产品是否含有粉末。例如：true，false。
     * @param has_liquid          可选产品是否含有液体。例如：true，false。
     * @param has_battery         可选产品是否含有电池。例如：true，false。
     * @param has_metal           可选产品是否含有金属。例如：true，false。
     */
    public ApiResult productAdd(String id, String name, String description, String declared_name, String declared_local_name,
                                String pieces, String tags, String sku, String color, String size, String inventory, String price,
                                String shipping, String msrp, String shipping_time, String main_image, String parent_sku, String brand,
                                String landing_page_url, String upc, String extra_images, String max_quantity, String length, String width,
                                String height, String weight, String declared_value, String hscode, String origin_country, String has_powder,
                                String has_liquid, String has_battery, String has_metal) {

        //获取门店
        ShopWish shopWishs = shopMapper.getShopWishById(id);
        String access_token = shopWishs.getToken();
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", access_token);
        if (StringUtils.isEmpty(name)) {
            return new ApiResult(405, "产品名称必填");
        }
        params.put("name", name);
        if (StringUtils.isEmpty(description)) {
            return new ApiResult(405, "产品描述必填");
        }
        params.put("description", description);
        if (StringUtils.isNotEmpty(declared_name)) {
            params.put("declared_name", declared_name);
        }
        if (StringUtils.isNotEmpty(declared_local_name)) {
            params.put("declared_local_name", declared_local_name);
        }
        if (StringUtils.isNotEmpty(pieces)) {
            params.put("pieces", pieces);
        }
        if (StringUtils.isNotEmpty(pieces)) {
            params.put("pieces", pieces);
        }
        if (StringUtils.isEmpty(tags)) {
            return new ApiResult(405, "tags述产品的字符串必填");
        }
        params.put("tags", tags);
        if (StringUtils.isEmpty(sku)) {
            return new ApiResult(405, "sku必填");
        }
        params.put("sku", sku);
        if (StringUtils.isNotEmpty(color)) {
            params.put("color", color);
        }
        if (StringUtils.isNotEmpty(size)) {
            params.put("size", size);
        }
        if (StringUtils.isEmpty(inventory)) {
            return new ApiResult(405, "inventory库存必填");
        }
        params.put("inventory", inventory);
        if (StringUtils.isEmpty(price)) {
            return new ApiResult(405, "price商品单价必填");
        }
        params.put("price", price);
        if (StringUtils.isEmpty(shipping)) {
            return new ApiResult(405, "shipping配送必填");
        }
        params.put("shipping", shipping);
        if (StringUtils.isNotEmpty(msrp)) {
            params.put("msrp", msrp);
        }
        if (StringUtils.isNotEmpty(shipping_time)) {
            params.put("shipping_time", shipping_time);
        }
        if (StringUtils.isNotEmpty(main_image)) {
            params.put("main_image", main_image);
        }
        if (StringUtils.isNotEmpty(parent_sku)) {
            params.put("parent_sku", parent_sku);
        }
        if (StringUtils.isNotEmpty(brand)) {
            params.put("brand", brand);
        }
        if (StringUtils.isNotEmpty(landing_page_url)) {
            params.put("landing_page_url", landing_page_url);
        }
        if (StringUtils.isNotEmpty(upc)) {
            params.put("upc", upc);
        }
        if (StringUtils.isNotEmpty(extra_images)) {
            params.put("extra_images", extra_images);
        }
        if (StringUtils.isNotEmpty(max_quantity)) {
            params.put("max_quantity", max_quantity);
        }
        if (StringUtils.isNotEmpty(length)) {
            params.put("length", length);
        }
        if (StringUtils.isNotEmpty(width)) {
            params.put("width", width);
        }
        if (StringUtils.isNotEmpty(height)) {
            params.put("height", height);
        }
        if (StringUtils.isNotEmpty(weight)) {
            params.put("weight", weight);
        }
        if (StringUtils.isNotEmpty(declared_value)) {
            params.put("declared_value", declared_value);
        }
        if (StringUtils.isNotEmpty(hscode)) {
            params.put("hscode", hscode);
        }
        if (StringUtils.isNotEmpty(origin_country)) {
            params.put("origin_country", origin_country);
        }
        if (StringUtils.isNotEmpty(has_powder)) {
            params.put("has_powder", has_powder);
        }
        if (StringUtils.isNotEmpty(has_liquid)) {
            params.put("has_liquid", has_liquid);
        }
        if (StringUtils.isNotEmpty(has_battery)) {
            params.put("has_battery", has_battery);
        }
        if (StringUtils.isNotEmpty(has_metal)) {
            params.put("has_metal", has_metal);
        }
        String result = StringUtils.jsonPost(wishUrl + "/product/add", params);
        if (StringUtils.isNotEmpty(result)) {
            JSONObject json = JSONObject.fromObject(result);
            int code = json.getInt("code");
            if (code == 0) {
                return new ApiResult(200, "添加成功");
            }
        }
        return new ApiResult(405, "添加失败");
    }

    //wish通知
    public ApiResult wishTicket(String userId) {
        List<ShopWish> shopWishs = shopMapper.getShopWish(userId);
        if (shopWishs == null || shopWishs.size() == 0) {
            logger.info("");
        }
        for (ShopWish shopWish : shopWishs) {
            StringBuffer url = new StringBuffer(wishUrl + "/ticket/get-action-required?");
            url.append("access_token=" + shopWish.getToken());
            url.append("&start=" + "0");
            url.append("&limit=" + "100");
            String result = StringUtils.httpURLConectionGET(url.toString());
            while (StringUtils.isNotEmpty(result)) {
                JSONObject json = JSONObject.fromObject(result);
                result = "";
                int code = json.getInt("code");
                if (code == 0) {
                    JSONArray data = json.getJSONArray("data");
                    //遍历数组获取元素----对象
                    analysisJsonNotice(shopWish.getId(), shopWish.getShopUserId(), data);
                    JSONObject paging = json.optJSONObject("paging");//下一页
                    if (paging != null) {
                        if (paging.has("next")) {
                            String next = paging.getString("next");
                            result = StringUtils.httpURLConectionGET(next);
                            continue;
                        }
                    }
                } else {
                    return new ApiResult(405, "https://merchant.wish.com/oauth/authorize?client_id=" + shopWish.getClientId(), shopWish.getShopName() + "店铺授权码过期，请重新授权");
                }
            }
        }
        return null;
    }

    //将json信息转换成对象
    public void analysisJsonNotice(String orderStoreId, String shopUserId, JSONArray data) {
        for (int i = 0; i < data.size(); i++) {
            JSONObject child = data.getJSONObject(i);
            JSONObject ticket = child.optJSONObject("Ticket");//

            String id = ticket.getString("id");
            SysTicket n = shopMapper.getSysTicket(id);
            SysTicket sysTicket = new SysTicket();

            sysTicket.setId(id);
            sysTicket.setShopStoreId(orderStoreId);
            sysTicket.setUserId(shopUserId);
            sysTicket.setPlatformType("3");
            sysTicket.setStatus("0");

            String addtime = ticket.getString("open_date");//故障单创建的日期
            sysTicket.setAddTime(addtime.replace("T", " "));
            String update = ticket.getString("last_update_date");//故障单上次更新的时间
            sysTicket.setUpdTime(update.replace("T", " "));
            String label = ticket.getString("label");//标签
            sysTicket.setLabel(label);
            String subject = ticket.getString("subject");//主题
            sysTicket.setSubject(subject);

            //删除回复的信息
            shopMapper.delTicketReply(id);
            JSONArray replies = ticket.getJSONArray("replies");
            for (int j = 0; j < replies.size(); j++) {
                JSONObject child2 = replies.getJSONObject(j);
                JSONObject reply = child2.optJSONObject("Reply");
                String sender = reply.getString("sender");//类型
                String date = reply.getString("date");//回复时间
                String message = reply.getString("message");//回复信息
                if (StringUtils.equals("user", sender)) {
                    message = reply.getString("translated_message_zh");//回复信息
                }
                SysTicketReply sysTicketReply = new SysTicketReply(id, sender, date.replace("T", " "), message);
                shopMapper.saveSysTicketReply(sysTicketReply);
            }

            if (n == null) {
                //添加系统消息
                shopMapper.saveSysTicket(sysTicket);
            }
        }
    }

    //wish-客服信息回复
    public ApiResult wishReply(String id, String reply) {
        SysTicket sysTicket = shopMapper.getSysTicket(id);
        //获取门店
        ShopWish shopWish = shopMapper.getShopWishById(sysTicket.getShopStoreId());
        StringBuffer url = new StringBuffer(wishUrl + "/ticket/reply?");
        url.append("access_token=" + shopWish.getToken());
        url.append("&id=" + id);
        url.append("&reply=" + reply);
        String result = StringUtils.httpURLConectionGET(url.toString());
        if (StringUtils.isNotEmpty(result)) {
            JSONObject json = JSONObject.fromObject(result);
            int code = json.getInt("code");
            if (code == 0) {
                SysTicketReply sysTicketReply = new SysTicketReply(id, "merchant", DateUtil.getYMDHMSDate(), reply);
                shopMapper.saveSysTicketReply(sysTicketReply);
                return new ApiResult(200, "回复成功");
            }
        }
        return new ApiResult(405, "回复失败");
    }

    //客服信息关闭
    public ApiResult wishClose(String id) {
        SysTicket sysTicket = shopMapper.getSysTicket(id);
        //获取门店
        ShopWish shopWish = shopMapper.getShopWishById(sysTicket.getShopStoreId());
        StringBuffer url = new StringBuffer(wishUrl + "/ticket?");
        url.append("access_token=" + shopWish.getToken());
        url.append("&id=" + id);
        String result = StringUtils.httpURLConectionGET(url.toString());
        if (StringUtils.isNotEmpty(result)) {
            JSONObject json = JSONObject.fromObject(result);
            int code = json.getInt("code");
            if (code == 0) {
                sysTicket.update();
                shopMapper.wishClose(sysTicket);
                return new ApiResult(200, "回复成功");
            }
        }
        return new ApiResult(405, "回复失败");
    }
}
